import numpy as np
import matplotlib.pyplot as plt
import math
from scipy.integrate import quad

# 中文和负号的正常显示
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

def visualize_circle_area():
    """可视化四分之一圆面积的计算"""
    # 创建半圆曲线
    x = np.linspace(0, 2, 1000)
    y = np.sqrt(4 - x**2)
    
    fig, ax = plt.subplots(figsize=(10, 8))
    
    # 绘制四分之一圆
    ax.plot(x, y, 'b-', linewidth=3, label='y = √(4-x²)')
    ax.fill_between(x, y, alpha=0.3, color='blue')
    
    # 添加标注
    ax.text(1, 0.7, '四分之一圆区域', fontsize=12, ha='center')
    ax.text(1, 0.5, '面积 = π', fontsize=12, ha='center')
    
    # 设置坐标轴
    ax.set_xlim(0, 2.5)
    ax.set_ylim(0, 2.5)
    ax.set_xlabel('x')
    ax.set_ylabel('y')
    ax.set_title('四分之一圆: $\int_0^2 \sqrt{4 - x^2}  dx = \pi$')
    ax.grid(True, alpha=0.3)
    ax.set_aspect('equal')
    
    # 添加坐标轴箭头
    ax.arrow(0, 0, 2.2, 0, head_width=0.05, head_length=0.1, fc='k', ec='k')
    ax.arrow(0, 0, 0, 2.2, head_width=0.05, head_length=0.1, fc='k', ec='k')
    
    plt.show()
    
    # 计算数值结果
    theoretical_area = math.pi
    numerical_area, error = quad(lambda x: np.sqrt(4-x**2), 0, 2)
    
    print(f"理论值 (π): {theoretical_area:.10f}")
    print(f"数值计算: {numerical_area:.10f}")
    print(f"绝对误差: {abs(numerical_area - theoretical_area):.2e}")

visualize_circle_area()